/* This file is part of swapper project
 *
 * Copyright (C) 2020 The Swapper Project Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.swapper.regexp;

import java.util.Objects;
import java.util.Random;

/**
 * The regular expression fixed node.
 * Fixed the matching regular expression node.
 * For example, in regular expression "abc",
 * "a", "b", and "c" are fixed nodes.
 */
final class CharacterNode extends PatternNode {
  private final int codePoint;
  private final String fixedRandomResult;

  /**
   * Public constructor.
   *
   * @param context   the generator context.
   * @param character the fixed character.
   */
  public CharacterNode(PatternReverser context, char character) {
    super(context);
    if (Character.isSurrogate(character)) {
      throw new IllegalArgumentException("The character is surrogate.");
    }
    this.codePoint = character;
    this.fixedRandomResult = Character.toString(character);
  }

  /**
   * Public constructor.
   *
   * @param context   the generator context.
   * @param codePoint the fixed character code point.
   */
  public CharacterNode(PatternReverser context, int codePoint) {
    super(context);
    if (!Character.isValidCodePoint(codePoint)) {
      throw new IllegalArgumentException("The specified code point is invalid.");
    }
    this.codePoint = codePoint;
    this.fixedRandomResult = CharacterHelper.codePointToString(codePoint);
  }

  public int codePoint() {
    return codePoint;
  }

  /**
   * Gets the random weight.
   * There's only one case.
   *
   * @return the random weight.
   */
  @Override
  public int weight() {
    return 1;
  }

  @Override
  public String random(Random random) {
    return fixedRandomResult;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o instanceof CharacterNode) {
      return codePoint == ((CharacterNode) o).codePoint;
    }
    return false;
  }

  @Override
  public int hashCode() {
    return Objects.hash(codePoint);
  }
}
